package com.example.demo.controller;

import com.example.demo.entity.Comment;
import com.example.demo.service.CommentService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;
    @Autowired
    private MessageController messageController;
    @PostMapping("/saveComment")
    public Map<String, Object> addComment(
            @RequestParam Long postId, // 帖子 ID
            @RequestParam(required = false) Long parentCommentId, // 父评论 ID（允许为空）
            @RequestParam String content, // 评论内容
            HttpServletRequest request) {

        // 获取当前用户
        var currentUser = userService.getCurrentUser(request);
        if (currentUser == null) {
            return Map.of("code", 401, "message", "用户未登录");
        }

        // 构建评论对象
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setUserId(currentUser.getId());
        comment.setParentCommentId(parentCommentId); // 允许为空
        comment.setContent(content);

        // 添加评论
        commentService.addComment(comment);
        // 调用消息发送接口
        messageController.sendMessage(postId, "comment", request);
        return Map.of("code", 200, "message", "评论成功");
    }

    // 获取帖子的评论列表
    @GetMapping("/{postId}")
    public Map<String, Object> getCommentsByPostId(@PathVariable Long postId, HttpServletRequest request) {
        var comments = commentService.getCommentsByPostId(postId, request);
        return Map.of("code", 200, "message", "success", "comments", comments);
    }

    // 获取二级评论
    @GetMapping("/replies/{parentCommentId}")
    public Map<String, Object> getRepliesByParentCommentId(@PathVariable Long parentCommentId) {
        var replies = commentService.getRepliesByParentCommentId(parentCommentId);
        return Map.of("code", 200, "message", "success", "replies", replies);
    }

    // 获取帖子的评论总数
    @GetMapping("/count/{postId}")
    public Map<String, Object> getCommentCountByPostId(@PathVariable Long postId) {
        int commentCount = commentService.getCommentCountByPostId(postId);
        return Map.of("code", 200, "message", "success", "commentCount", commentCount);
    }

    // 获取帖子的二级评论总数
    @GetMapping("/reply-count/{postId}")
    public Map<String, Object> getReplyCountByPostId(@PathVariable Long postId) {
        int replyCount = commentService.getReplyCountByPostId(postId);
        return Map.of("code", 200, "message", "success", "replyCount", replyCount);
    }
}
